package com.java.basis.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j(topic = "c.TestThreadPoolExecutor")
public class TestThreadPoolExecutor {
    public static void main(String[] args) {
        AtomicInteger c = new AtomicInteger(1);
        ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(2);
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                2,
                3,
                0,
                TimeUnit.MILLISECONDS,
                queue,
                r -> new Thread(r, "myThread" + c.getAndIncrement()),
                new ThreadPoolExecutor.AbortPolicy()
        );
        showState(queue, threadPoolExecutor);
        threadPoolExecutor.submit(new MyTask("1", 3600000));
        showState(queue, threadPoolExecutor);
        threadPoolExecutor.submit(new MyTask("2", 3600000));
        showState(queue, threadPoolExecutor);
        threadPoolExecutor.submit(new MyTask("3", 3600000));
        showState(queue, threadPoolExecutor);
        threadPoolExecutor.submit(new MyTask("4", 3600000));
        showState(queue, threadPoolExecutor);
        threadPoolExecutor.submit(new MyTask("5", 3600000));
        showState(queue, threadPoolExecutor);
        threadPoolExecutor.submit(new MyTask("6", 3600000));
        showState(queue, threadPoolExecutor);

    }

    static class MyTask implements Runnable {
        private final String name;
        private final long duration;
        public MyTask(String name, long duration) {
            this.name = name;
            this.duration = duration;
        }

        @Override
        public void run() {
            try {
                log.debug("running..." + this);
                Thread.sleep(duration);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

    private static void showState(ArrayBlockingQueue<Runnable> queue, ThreadPoolExecutor threadPool) {
        System.out.println("size: " + threadPool.getPoolSize() + " queue: " + queue);
    }
}
